package com.example.systema.shiro;

import com.example.systema.domain.User;
import com.example.systema.service.MenuService;
import com.example.systema.service.RoleService;
import com.example.systema.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    /**
     * 授权操作
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权逻辑操作
        Object obj = SecurityUtils.getSubject().getPrincipal(); //获取用户信息
        User user = (User) obj;
        Set<String> roles = new HashSet<String>();  //角色列表
        Set<String> menus = new HashSet<String>();  //资源列表
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        roles = roleService.selectRoleKeys(user.getUserId());
        menus = menuService.selectPermsByUserId(user.getUserId());
        // 角色加入AuthorizationInfo认证对象
        info.setRoles(roles);
        // 权限加入AuthorizationInfo认证对象
        info.setStringPermissions(menus);
        return info;
    }

    /**
     * 认证操作
     *
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) arg; //获取封装好的前台传递过来的用户信息

        User dbUser = userService.findByname(token.getUsername());
        if (null == dbUser) {
            return null;
        }

        //校验用户密码，成功返回用户信息
        return new SimpleAuthenticationInfo(dbUser, dbUser.getPassword(), "");
    }
}
